import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qunaimedical/components/custom_text_field.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

class ResetPasswordPage extends StatefulWidget {
  static const String routeName = '/reset_pwd';

  const ResetPasswordPage({Key? key}) : super(key: key);

  @override
  _ResetPasswordPageState createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _pwd1Controller = TextEditingController();
  final TextEditingController _pwd2Controller = TextEditingController();
  bool _showPwd1 = false;
  bool _showPwd2 = false;
  bool _codeSend = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("重置密码")),
      body: CommonUtil.generateWidgetOfWideScreen(_buildBody()),
    );
  }

  Widget _buildBody() {
    return ListView(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
      children: [
        Container(
          padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(16))),
          child: Column(
            children: [
              CustomTextField(
                controller: _phoneController,
                textInputAction: TextInputAction.next,
                hintText: "请输入手机号",
                label: "手机号",
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(11),
                ],
                onChanged: (value) {
                  setState(() {});
                },
                suffixIcon: _phoneController.text.isNotEmpty
                    ? IconButton(
                        icon: const Icon(CupertinoIcons.xmark_circle,
                            color: Colors.grey),
                        onPressed: () {
                          setState(() {
                            _phoneController.clear();
                          });
                        })
                    : null,
              ),
              CustomTextField(
                controller: _pwd1Controller,
                label: "新密码",
                hintText: "请输入密码",
                textInputAction: TextInputAction.next,
                obscureText: !_showPwd1,
                suffixIcon: IconButton(
                    icon: _showPwd1
                        ? const Icon(CupertinoIcons.eye, color: Colors.grey)
                        : Image.asset(
                            'assets/images/ic_eye_close.png',
                            width: 20,
                            height: 20,
                            color: Colors.grey,
                          ),
                    onPressed: () {
                      setState(() {
                        _showPwd1 = !_showPwd1;
                      });
                    }),
              ),
              CustomTextField(
                controller: _pwd2Controller,
                hintText: "请再次输入密码",
                label: "确认密码",
                textInputAction: TextInputAction.next,
                obscureText: !_showPwd2,
                suffixIcon: IconButton(
                    icon: _showPwd2
                        ? const Icon(CupertinoIcons.eye, color: Colors.grey)
                        : Image.asset(
                            'assets/images/ic_eye_close.png',
                            width: 20,
                            height: 20,
                            color: Colors.grey,
                          ),
                    onPressed: () {
                      setState(() {
                        _showPwd2 = !_showPwd2;
                      });
                    }),
              ),
              CustomTextField(
                controller: _codeController,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(6),
                ],
                hintText: "请输入验证码",
                label: "验证码",
                suffixIcon: TextButton(
                  onPressed: _codeSend ? null : _getCode,
                  child: Text(_codeSend ? "验证码已发送" : "获取验证码"),
                ),
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 20.0),
          child: Text(
            "请设置至少6位数的密码",
            style: Theme.of(context).textTheme.caption,
          ),
        ),
        PrimaryButton(
          "确定",
          onPressed: _confirmResetPassword,
          margin: const EdgeInsets.symmetric(vertical: 20),
        ),
      ],
    );
  }

  void _getCode() async {
    CommonUtil.hideKeyboard(context);
    String phone = _phoneController.text.trim();
    if (phone.length != 11) {
      ToastUtil.show("请输入有效的手机号");
      return;
    }
    DialogUtil.showWaitDialog(context);
    try {
      Response response = await XHttp.instance.post(
        Urls.SEND_OTP,
        queryParameters: {"phone": phone},
      );
      if (mounted) {
        Navigator.pop(context);
        if (response.data == "success") {
          setState(() {
            _codeSend = true;
          });
        } else {
          ToastUtil.show("验证码错误，请重新获取验证码。");
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        Navigator.pop(context);
        CommonUtil.catchDioError(e);
      }
    }
  }

  void _confirmResetPassword() async {
    CommonUtil.hideKeyboard(context);
    String phone = _phoneController.text.trim();
    String pwd1 = _pwd1Controller.text.trim();
    String pwd2 = _pwd2Controller.text.trim();
    String code = _codeController.text.trim();
    if (pwd1.isEmpty || pwd2.isEmpty) {
      ToastUtil.show("密码不能为空");
      return;
    }
    if (pwd1.length < 6 || pwd2.length < 6) {
      ToastUtil.show("请输入至少6位数密码");
      return;
    }
    if (code.isEmpty) {
      ToastUtil.show("请输入验证码");
      return;
    }
    DialogUtil.showWaitDialog(context);
    try {
      Response response = await XHttp.instance.post(
        Urls.RESET_PWD,
        queryParameters: {
          "phoneNumber": phone,
          "text2": code,
          "password": pwd1,
        },
      );
      if (mounted) {
        if (response.data == "ok") {
          // 重置成功，返回界面
          Navigator.popUntil(context, ModalRoute.withName(LoginPage.routeName));
        } else {
          // 出错
          Navigator.pop(context);
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        Navigator.pop(context);
        CommonUtil.catchDioError(e);
      }
    }
  }
}
